import {Fragment, useState} from 'react';
import { Prompt } from 'react-router-dom';
import { useForm} from "react-hook-form";

import Card from '../UI/Card';
import LoadingSpinner from '../UI/LoadingSpinner';
import classes from './QuoteForm.module.css';

const QuoteForm = (props) => {
  const [isEntering, setIsEntering] = useState(false);
  const {
    register,
    handleSubmit,
  } = useForm();

  function submitFormHandler(data) {

    props.onAddQuote({ author: data.author, text: data.text });
  }

  const formFocusedHandler = () => {
    setIsEntering(true);
  };

  const finishEnteringHandler = () => {
    setIsEntering(false);
  };

  return (
      <Fragment>
        <Prompt when={isEntering} message={
          (location) => '你确定想离开此页吗? 你所输入的信息将会被清空哦!' } />
        <Card>
          <form onFocus={formFocusedHandler} className={classes.form}
                onSubmit={
                  handleSubmit(submitFormHandler)
                }>
            {props.isLoading && (
              <div className={classes.loading}>
                <LoadingSpinner />
              </div>
            )}

            <div className={classes.control}>
              <label htmlFor='author'>作者</label>
              <input type='text' id='author'
                     {...register('author', {required: true})} />
            </div>
            <div className={classes.control}>
              <label htmlFor='text'>名言</label>
              <textarea id='text' rows='5' {...register('text', {
                required: true,
                maxLength: 100,
                minLength: 2,
              })} />
            </div>
            <div className={classes.actions}>
              <button onClick={finishEnteringHandler} className='btn'>添加新名言</button>
            </div>
          </form>
        </Card>
      </Fragment>
  );
};

export default QuoteForm;
